const co = require('co');
const OSS = require('ali-oss');
const fs = require('fs');
const request = require('request');
var wechat = require('./wechat');

var client = new OSS({
  region: 'oss-ap-southeast-2',
  accessKeyId: 'LTAI38mNPzqBgOt3',
  accessKeySecret: 'cQ5zBAUJM5w4OJoc5nUGmTY6hBWdFv',
  bucket: 'auewe'
});

module.exports = {

  download_meadia: function (media_id, order_id, callback) {
    // var access_token = yield *wechat.getAccessTokenSync();
    // console.log('get token sync:', access_token);
    // var get_img_url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token='+access_token+'&media_id='+media_id;
    // request(get_img_url).pipe(client.putStream(order_id+'.jpg'));
    wechat.getAccessToken(function (call) {
      var get_img_url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token='+call+'&media_id='+media_id;
      request.get(get_img_url).pipe(fs.createWriteStream('assets/img/'+order_id+'.jpeg').on('finish', function () {
        co(function *() {
          var read_stream = fs.createReadStream('assets/img/'+order_id+'.jpeg');
          var result = yield client.putStream('transfer_snap/'+order_id+'.jpeg', read_stream);
          console.log(result);
          fs.unlink('assets/img/'+order_id+'.jpeg', function (err) {
            if (err) console.log(err);
            return callback('ok');
          })
        })
      }))
    })
  }
}
